﻿using Autofac;
using MediatR.Pipeline;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using Reborn.MicroKernel.Interface;
using Autofac.Extensions.DependencyInjection;

namespace Reborn.MicroKernel.Register
{
    /// <summary>
    /// 启动项注册
    /// </summary>
    internal class BootstrapRegister
    {
        /// <summary>
        /// 处理者
        /// </summary>
        /// <param name="assemblies"></param>
        /// <param name="containerBuilder"></param>
        public static void Handler(Config config)
        {
            if (config.RegisterAssembly == null || config.RegisterAssembly.Length == 0) return;

            var builder = new ContainerBuilder();

            var mediatrOpenTypes = new[]
            {
                typeof(IBootstrap),
                typeof(ICofing),
                typeof(IRegister),
                typeof(IPreload),
                typeof(IEvents),
                typeof(ILoad),
                typeof(IGuardian),
            };

            foreach (var item in config.RegisterAssembly)
            {
                foreach (var mediatrOpenType in mediatrOpenTypes)
                {
                    builder.RegisterAssemblyTypes(item).Where( x => mediatrOpenType.IsAssignableFrom(x)).As<IRegisterBase>().AsSelf();
                }
            }

            var container = builder.Build();
            var pluginClasses = container.Resolve<IEnumerable<IRegisterBase>>();

            foreach (var pluginClass in pluginClasses)
            {
                try
                {
                    pluginClass.Handle();
                }
                catch (Exception ex)
                { 
                
                }
            }

            container.Dispose();

        }
    }
}
